package com.efounder.zone.widget;

import android.content.Context;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentManager;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.utils.Constants;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.utils.ResStringUtil;
import com.efounder.zone.R;
import com.efounder.zone.bean.TalksBean;
import com.efounder.zone.event.MobileZoneEvent;
import com.efounder.zone.event.MobileZoneRefreshEvent;
import com.efounder.zone.util.CommentUtil;
import com.efounder.zone.util.CreateBeanUtil;
import com.efounder.zone.util.ZoneRequestUtil;

import com.utilcode.util.ActivityUtils;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Richard on 2018/5/9.
 * <p>
 * 点赞，评论，转发View
 */

public class ThumbsCommentsTransmitView extends RelativeLayout implements View.OnClickListener {

    public static final int MULTI = 100;//浏览次数因数
    //浏览次数
    private TextView tvViewNum;
    //点赞按钮
    private ImageView ivThumbs;
    //评论按钮
    private ImageView ivComment;
    //转发按钮
    private ImageView mTransmit;
    private TalksBean talksBean;
    //是否已经点赞
    private boolean isThumbsDone;
    //    private List<TalksBean> items;
    private int position;
    private FragmentManager fragmentManager;
    //    private MainZoneAdapter mainZonAdapter;
    private Context context;

    public ThumbsCommentsTransmitView(Context context) {
        super(context, null);
        this.context = context;
    }

    public ThumbsCommentsTransmitView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs, -1);
        this.context = context;
        initView();
    }

    public ThumbsCommentsTransmitView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
    }

    private void initView() {

        View.inflate(getContext(), R.layout.mobile_zone_item_thumbs, this);
        tvViewNum = (TextView) findViewById(R.id.mobile_zone_view_num);
        tvViewNum.setText(String.format(ResStringUtil.getString(R.string.zone_brow_time), "0"));
        ivThumbs = (ImageView) findViewById(R.id.mobile_zone_thumbs);
        ivComment = (ImageView) findViewById(R.id.mobile_zone_comments);
        mTransmit = (ImageView) findViewById(R.id.mobile_zone_transmit);

        ivThumbs.setOnClickListener(this);
        ivComment.setOnClickListener(this);
        mTransmit.setOnClickListener(this);
    }

    /**
     * 调用此方法显示浏览数量和是否点赞
     *
     * @param position
     */
    public void display(int position, TalksBean talksBean, FragmentManager fragmentManager) {
//        this.items = items;
        this.position = position;
        this.talksBean = talksBean;
        this.fragmentManager = fragmentManager;
        if (talksBean != null) {
            int count = talksBean.getObj().getReadCount() ;
            tvViewNum.setText(String.format(ResStringUtil.getString(R.string.zone_brow_time), count));
            List<TalksBean.LikesBean> likes = talksBean.getLikes();
            String userId = EnvironmentVariable.getProperty(Constants.CHAT_USER_ID);
            if (likes.toString().contains(userId)) {
                //本人点过赞
                ivThumbs.setSelected(true);
                isThumbsDone = true;
            } else {
                ivThumbs.setSelected(false);
                isThumbsDone = false;
            }
            if (likes == null) {
                ivThumbs.setSelected(false);
                isThumbsDone = false;
            }
        } else {
            ivThumbs.setSelected(false);
            isThumbsDone = false;
        }
    }


    @Override
    public void onClick(View view) {
        int id = view.getId();
        //点赞
        if (id == R.id.mobile_zone_thumbs) {
            requestThumbs();
            return;
        }
        //评论
        if (id == R.id.mobile_zone_comments) {
            CommentUtil.sendComment(context, position, null, talksBean, fragmentManager);
            return;
        }
        //转发
        if (id == R.id.mobile_zone_transmit) {
            CommentUtil.transmitContent(context, talksBean, fragmentManager);
            return;
        }
    }

    /**
     * 请求点赞接口
     */
    private void requestThumbs() {
        String TAG = "MainZoneAdapterThumbs";
        TalksBean.ObjBean obj = talksBean.getObj();
        int id = obj.getId();
        String userId = EnvironmentVariable.getProperty(Constants.CHAT_USER_ID);
        HashMap<String, String> params = new HashMap<>();
        params.put("userid", userId);
        params.put("id", userId);
        params.put("objecttype", String.valueOf(talksBean.getObjType()));
        params.put("objectid", String.valueOf(id));
        //如果已经点赞调用/likes/d 未点赞调用/likes
        String directory = isThumbsDone ? "/likes/d" : "/likes";
        if (!isThumbsDone)
            //执行点赞动画
            startAnimation();
        LoadingDataUtilBlack.show(ActivityUtils.getTopActivity(),ResStringUtil.getString(R.string.common_text_please_wait));
        ZoneRequestUtil.postCommonRequest(TAG, directory, params, new ZoneRequestUtil.ZoneRequestCallback() {
            @Override
            public void onSuccess(String response) {
                LoadingDataUtilBlack.dismiss();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    //点赞
                    if (jsonObject.getString("status").equals("106000")) {
                        if (jsonObject.getString("msg").contains("success")) {
                            ivThumbs.setSelected(true);
//                            handleNewLike(position);
                            TalksBean.LikesBean likesBean = new CreateBeanUtil().crateNewLikesBean();
                            if (talksBean.getLikes() == null) {
                                talksBean.setLikes(new ArrayList<TalksBean.LikesBean>());
                            }
                            talksBean.getLikes().add(likesBean);
                            //todo 设置积分
                            int integral = 0;
                            try {
                                integral = jsonObject.optInt("integral", talksBean.getObj().getIntegral());
                                talksBean.getObj().setIntegral(integral);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                            EventBus.getDefault().post(new MobileZoneEvent(position));
                        } else {
                            Toast.makeText(getContext(), R.string.zone_zan_fail_please_again, Toast.LENGTH_SHORT).show();
                            ivThumbs.setSelected(false);
                        }
                    }
                    //取消点赞
                    if (jsonObject.getString("status").equals("106001")) {
                        if (jsonObject.getString("msg").contains("success")) {
                            ivThumbs.setSelected(false);
//                            handleCancelLike(position);
                            List<TalksBean.LikesBean> likesBeanList = talksBean.getLikes();
                            for (int i = 0; i < likesBeanList.size(); i++) {
                                if (likesBeanList.get(i).getUserId() == Integer.valueOf(EnvironmentVariable.getProperty(Constants.CHAT_USER_ID))) {
                                    likesBeanList.remove(i);
                                }
                            }
                            int integral = 0;
                            try {
                                integral = jsonObject.optInt("integral", talksBean.getObj().getIntegral());
                                talksBean.getObj().setIntegral(integral);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            EventBus.getDefault().post(new MobileZoneEvent(position));
                        } else {
                            Toast.makeText(getContext(), R.string.zone_cancel_zan_fail_please_again, Toast.LENGTH_SHORT).show();
                            ivThumbs.setSelected(true);
                        }
                    }
                    //发事件刷新详情界面
                    EventBus.getDefault().post(new MobileZoneRefreshEvent(talksBean, null));

                } catch (Exception e) {
                    e.printStackTrace();
                    ivThumbs.setSelected(isThumbsDone);
                }
            }

            @Override
            public void onFail(String error) {
                LoadingDataUtilBlack.dismiss();
                Toast.makeText(getContext(), R.string.zone_zan_fail_please_again, Toast.LENGTH_SHORT).show();
                ivThumbs.setSelected(isThumbsDone);
            }
        });
    }

    /**
     * 点赞动画
     */
    private void startAnimation() {
        // [1]缩放(放大 缩小)1.0默认
        ScaleAnimation sa = new ScaleAnimation(1.0f, 1.4f, 1.0f, 1.4f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        // [2]设置动画执行的时长
        sa.setDuration(300);
        // [3]设置动画执行重复次数
        sa.setRepeatCount(1);
        // [4]设置重复的模式
        sa.setRepeatMode(Animation.REVERSE);
        // [3]iv执行动画
        ivThumbs.startAnimation(sa);
    }

    /**
     * 获取是否已经点赞了
     *
     * @return
     */
    public boolean getIsThumbsDone() {
        return isThumbsDone;
    }

}
